package com.jklan.zhiqibackend.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.jklan.zhiqibackend.common.ApiResponse;
import com.jklan.zhiqibackend.dto.request.LoginRequest;
import com.jklan.zhiqibackend.dto.request.RegisterRequest;
import com.jklan.zhiqibackend.entity.Users;
import com.jklan.zhiqibackend.service.UsersService;
import com.jklan.zhiqibackend.vo.response.LoginVO;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author 30688
 * @description UsersController
 */
@RestController
@RequestMapping("/auth")
public class UsersController {

    @Autowired
    private UsersService usersService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ApiResponse<String> register(@Valid @RequestBody RegisterRequest registerRequest) {
        usersService.register(registerRequest);
        return ApiResponse.success("注册成功");
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ApiResponse<LoginVO> login(@Valid @RequestBody LoginRequest loginRequest) {
        LoginVO loginVO = usersService.login(loginRequest);
        return ApiResponse.success(loginVO);
    }

    /**
     * 用户注销
     */
    @PostMapping("/logout")
    public ApiResponse<String> logout() {
        StpUtil.logout();
        return ApiResponse.success("注销成功");
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/me")
    public ApiResponse<LoginVO> getCurrentUser() {
        Long userId = StpUtil.getLoginIdAsLong();
        Users user = usersService.getById(userId);

        LoginVO loginVO = new LoginVO();
        BeanUtils.copyProperties(user, loginVO);
        loginVO.setToken(StpUtil.getTokenValue());

        return ApiResponse.success(loginVO);
    }

    /**
     * 检查用户名是否已存在
     */
    @GetMapping("/check-username")
    public ApiResponse<Boolean> checkUsername(@RequestParam String username) {
        boolean exists = usersService.checkUsernameExists(username);
        return ApiResponse.success(exists);
    }

    /**
     * 检查邮箱是否已存在
     */
    @GetMapping("/check-email")
    public ApiResponse<Boolean> checkEmail(@RequestParam String email) {
        boolean exists = usersService.checkEmailExists(email);
        return ApiResponse.success(exists);
    }
}
